package yunwo.cn.yzstation.api.okapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import yunwo.cn.yzstation.bean.Bean;

public abstract class BaseCallBack<T> extends Callback<T> {
    Class mClass;
    private Context mContext;
    private boolean mIsShowDialog;
    private ProgressDialog progressDialog;
    //    private CustomDialog mCustomDialog;
    private Request mRequest;
    public static Gson mGson = new Gson();
    private ProgressDialog mMyDialog;

    public BaseCallBack(Class targetClazz, Context context, boolean isShowDialog) {
        mClass = targetClazz;
        mContext = context;
        mIsShowDialog = isShowDialog;
    }

    public BaseCallBack(Class<T> targetClazz, Context mContext) {
        this(targetClazz, mContext, true);//默认不开启动画
    }


    @Override
    public T parseNetworkResponse(Response response, int id) throws Exception {

        T t = null;
        try {
            String result = response.body().string();

            Log.d("服务器响应内容::", result);

            t = (T) mGson.fromJson(result, mClass);

        } catch (JsonSyntaxException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        return t;
    }


    @Override
    public void onError(Call call, Exception e, int id) {
        //在这里做异常统一处理
        System.out.println("onError");
        myError(call, e, id);
    }

    public abstract void myError(Call call, Exception e, int id);

    @Override
    public void onBefore(Request request, int id) {
        //这里开启动画
        mRequest = request;
        if (mIsShowDialog && mContext != null) {
            if (mMyDialog == null) {
                mMyDialog = ProgressDialog.show(mContext, null, "请稍等...");
                mMyDialog.setCancelable(false);
               /* mCustomDialog = new CustomDialog(mContext, R.style.CustomDialog);
                mCustomDialog.setCancelable(false);*/
            }
            if (mContext instanceof Activity && !((Activity) mContext).isFinishing()) {
//                mCustomDialog.show();
                mMyDialog.show();
            }
        }

        super.onBefore(request, id);
    }

    @Override
    public void onAfter(int id) {
        try {

            if (mMyDialog != null && mMyDialog.isShowing()) {
                mMyDialog.dismiss();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}